//
//  SetCardViewController.m
//  QRMaster
//
//  Created by myApple on 15/5/5.
//  Copyright (c) 2015年 myApple. All rights reserved.
//

#import "SetCardViewController.h"
#import "ALLURLHeader.h"
#import "RequestNetWork.h"
#import "ZXMultiFormatWriter.h"
#import "ZXImage.h"
#import "ZXingObjC.h"
#import "Reachability.h"
#import "PromptInfoView.h"

@interface SetCardViewController ()
{
    UILabel * titleLabel;
    UIImageView * HouseCardImgView;
    UILabel * cardNumberLabel;
    
    int allNumber[256];
    int indexZero[34];
    char replace;
    
    UIActivityIndicatorView * _activityIndicator;
}

@end

@implementation SetCardViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self prepareView];
        [self prepareActivityIndicator];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(CheckAuthData:) name:@"authorAndSet" object:nil];
    self.view.backgroundColor = BACKCOLOR;
    
}

-(void)prepareView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float ScreenHeight = [UIScreen mainScreen].bounds.size.height;
    float x = 0;
    float y = 20;
    float width = ScreenWidth;
    float height = 44;
    
    UIView  * titleView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    titleView.backgroundColor = TOPCOLOR;
    titleView.userInteractionEnabled = YES;
    [self.view addSubview:titleView];
    
    //返回图标
    x = 10;
    y = 0;
    height = 40;
    width = 40;
    UIImage * backImage = [UIImage imageNamed:@"24X24"];
    UIButton * backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(x, y, width, height);
    [backBtn setImage:backImage forState:0];
    [backBtn addTarget:self action:@selector(BackClick) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:backBtn];
    
    
    x += width + 15;
    y = 12;
    height = 20;
    width = 80;
    titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.font = [UIFont systemFontOfSize:16.0];
    [titleView addSubview:titleLabel];
    
    //二维码房卡
//    x = ScreenWidth / 2.0 - 90;
//    y = ScreenHeight / 3.0 - 90;
//    width = 180;
//    height = 180;
    x = ScreenWidth / 2.0 - 130;
    y = ScreenHeight / 3.0 - 110;
    width = 260;
    height = 260;
    if (KScreenIphone4 == 480) {
        y = ScreenHeight / 3.0 - 80;
        x = ScreenWidth / 2.0 - 110;
        width = 220;
        height = 220;
    }

    HouseCardImgView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    HouseCardImgView.userInteractionEnabled = YES;
    [self.view addSubview:HouseCardImgView];
    UITapGestureRecognizer * refreshCardView = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(refreshCard)];
    [HouseCardImgView addGestureRecognizer:refreshCardView];
   
    y += height + 20;
    height = 40;
    UIView * cardView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    cardView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:cardView];
    
    
    x = cardView.frame.size.width/ 2.0 - 60;
    y = 10;
    height = 20;
    width = 60;
    UILabel * cardLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    cardLabel.text = @"房号:";
    cardLabel.font = [UIFont systemFontOfSize:14.0];
    cardLabel.textAlignment = NSTextAlignmentRight;
    [cardView addSubview:cardLabel];
    
    x = cardView.frame.size.width/ 2.0;
    width = cardView.frame.size.width / 2.0;
    cardNumberLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    cardNumberLabel.font = [UIFont systemFontOfSize:14.0];
    [cardView addSubview:cardNumberLabel];
    
    
    x = cardView.frame.origin.x;
    y = cardView.frame.origin.y + cardView.frame.size.height + 15;
    width = cardView.frame.size.width;
    height = 60;
    UILabel * textLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    textLabel.text = @"请将二维码贴近并对准门禁扫描器，扫描失败请直接点击二维码图片刷新";
    textLabel.numberOfLines = 0;
    textLabel.font = [UIFont systemFontOfSize:12.0];
    textLabel.textColor = GREENCOLOR;
    [self.view addSubview:textLabel];
}

-(void)getcheckAuthData:(NSString *)type
{
    if ([self IsHaveNetwork]) {
        return;
    }
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    [_dict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [_dict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [_dict setValue:[NSString stringWithFormat:@"%d",30] forKey:@"validTime"];
    [_dict setValue:type forKey:@"type"];
    [RequestNetWork  initWithPath:POST(CHECKAUTHORTIY) requestType:KTypePost flag:@"authorAndSet" params:_dict actvitity:_activityIndicator];
}

-(void)CheckAuthData:(NSNotification *)not
{
    NSDictionary * dict = [not.userInfo objectForKey:@"data"];
    NSString * string = [dict objectForKey:@"cardString"];
    [self stringFromHexString:string];
}

-(void)stringFromHexString:(NSString *)hexString {
    
    char *myBuffer = (char *)malloc((int)[hexString length] / 2 + 1);
    int t = 0;
    bzero(myBuffer, [hexString length] / 2 + 1);
    for (int i = 0; i < [hexString length] - 1; i += 2) {
        unsigned int anInt;
        NSString * hexCharStr = [hexString substringWithRange:NSMakeRange(i, 2)];
        NSScanner * scanner = [[NSScanner alloc] initWithString:hexCharStr];
        [scanner scanHexInt:&anInt];
        //三十四个数字，根据下标来找到零的位置
        if (anInt == 0) {
            indexZero[t] = i/2;
            t++;
        }
        //256个数字，去掉出现的数字，再从没有出现过的数字随便拿一个来替换0
        for (int j = 0; j<256; j++) {
            if (anInt == allNumber[j]) {
                allNumber[j] = 0;
                break;
            }
        }
        myBuffer[i / 2] = (char)anInt;
    }
    //替换0的数字
    for (int k = 0; k< 256; k++) {
        if (allNumber[k] != 0) {
            replace = (char)allNumber[k];
            break;
        }
    }
    //通过下标来找为零的位置将其替换掉
    for (int j = 0; j< 34; j++) {
        if (indexZero[j] != 0) {
            myBuffer[indexZero[j]] = replace;
        }
    }
    NSString * replaceChar = [NSString stringWithFormat:@"%c",replace];
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingISOLatin1);
    NSString *unicodeString = [NSString stringWithCString:myBuffer encoding:enc];
    unicodeString = [unicodeString stringByReplacingOccurrencesOfString:replaceChar withString:@"\0"];
    [self prepareCardView:unicodeString];
}

-(void)prepareCardView:(NSString *)string
{
    if (!string) {
        return;
    }
    else
    {
        
        ZXMultiFormatWriter *writer = [[ZXMultiFormatWriter alloc] init];
        ZXBitMatrix *result = [writer encode:string
                                      format:kBarcodeFormatQRCode
                                       width:HouseCardImgView.frame.size.width
                                      height:HouseCardImgView.frame.size.width
                                       error:nil];
        
        if (result) {
            ZXImage *image = [ZXImage imageWithMatrix:result];
            if (image) {
                HouseCardImgView.image = [UIImage imageWithCGImage:image.cgimage];
            }
            else
            {
                HouseCardImgView.image = [UIImage imageNamed:@"bg"];
            }
        } else {
            HouseCardImgView.backgroundColor = [UIColor redColor];
        }
        
    }
    
}

-(void)setAuthorityOrSetting:(BOOL)authorityOrSetting
{
    _authorityOrSetting = authorityOrSetting;
}

-(void)setDict:(NSMutableDictionary *)dict
{
    _dict = dict;
    if (_authorityOrSetting) {
        [self getcheckAuthData:@"2"];
        titleLabel.text = @"授权";
    }
    else
    {
        titleLabel.text = @"配置";
        [self getcheckAuthData:@"4"];
    }
}

-(void)setRoomNumber:(NSString *)roomNumber
{
    _roomNumber = roomNumber;
    cardNumberLabel.text = _roomNumber;
}

//初始化风火轮
-(void)prepareActivityIndicator
{
    _activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    _activityIndicator.frame = CGRectMake(HouseCardImgView.frame.size.width / 2.0 -15, HouseCardImgView.frame.size.height - 15, 30, 30);
    _activityIndicator.hidden = NO;
    [HouseCardImgView addSubview:_activityIndicator];
}

-(void)refreshCard
{
    if (_authorityOrSetting) {
        [self getcheckAuthData:@"2"];
        titleLabel.text = @"授权";
    }
    else
    {
        titleLabel.text = @"配置";
        [self getcheckAuthData:@"4"];
    }
}

-(void)BackClick
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

//判断是否有网络
-(BOOL)IsHaveNetwork
{
    Reachability * reach = [Reachability reachabilityForInternetConnection];
    if([reach currentReachabilityStatus] == NotReachable) {
        [PromptInfoView showMessage:@"无法连接网络，请检查你的网络"];
        return YES;
    }
    return NO;
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
